package com.deyang.ui.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;


import com.deyang.callback.DialogProgressLoadCallback;
import com.deyang.callback.HttpDownLoadCallBack;
import com.deyang.callback.RequestPermissionsCallBack;
import com.deyang.callback.ValueCallBack;
import com.deyang.config.ConfigRes;
import com.deyang.config.HttpConfig;
import com.deyang.config.IntentConfig;
import com.deyang.entity.TokenInfo;
import com.deyang.maillist.R;
import com.deyang.service.IHttpService;
import com.deyang.tool.HttpTool;
import com.deyang.util.DialogUtil;
import com.deyang.util.HttpUtil;
import com.deyang.util.MyRxBarTool;
import com.deyang.util.PermissionUtil;
import com.deyang.util.ProjectFileUtil;
import com.deyang.util.RetrofitUtil;
import com.deyang.util.SpUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.et_userName)
    EditText etUserName;
    @BindView(R.id.iv_select)
    ImageView ivSelect;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.iv_hide)
    ImageView ivHide;

    @BindView(R.id.ll_content)
    LinearLayout llContent;
    @BindView(R.id.ll_userName)
    LinearLayout llUserName;

    private boolean isHide = true;


    private PopupWindow pw;
    private ListView lvSelectUserName;
    private List<String> userNameList;


    private IHttpService httpService;
    private HttpUtil httpUtil;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_login);
        MyRxBarTool.transparentStatusBar(this);//状态栏透明化
        ButterKnife.bind(this);

        ivHide.setImageResource(R.drawable.attention_light);
        ivSelect.setImageResource(R.drawable.down);
        InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(etUserName.getWindowToken(), 0);

    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {
        httpService = RetrofitUtil.buildRetrofit(this).create(IHttpService.class);
        httpUtil = new HttpUtil(this);

        //初始化登录过得用户名数据
        userNameList = SpUtil.getList(this, ConfigRes.STORAGE_USER_NAME_LIST);
        if (userNameList == null || userNameList.size() == 0) {
            userNameList = new ArrayList<>();
            ivSelect.setEnabled(false);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @OnClick({
            R.id.btn_login,
            R.id.iv_select,
            R.id.iv_hide,
    })
    @Override
    public void onClick(View v) {
        super.onClick(v);
        final String userName = etUserName.getText().toString();
        final String password = etPassword.getText().toString();
        switch (v.getId()) {
            case R.id.btn_login:
                login(userName, password);
                break;
            case R.id.iv_select:
                selectUserName();
                break;
            case R.id.iv_hide:
                hidePassword(password);
                break;
            default:
                break;
        }
    }

    /**
     * 显示与隐藏密码
     *
     * @param password
     */
    private void hidePassword(String password) {
        if (isHide) {
            etPassword.setInputType(InputType.TYPE_CLASS_TEXT);
            ivHide.setImageResource(R.drawable.attention_forbid);
            isHide = false;
        } else {
            etPassword.setInputType((InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD));
            ivHide.setImageResource(R.drawable.attention_light);
            isHide = true;
        }
        etPassword.setSelection(password.length());
    }

    /**
     * 选择缓存用户名
     */
    private void selectUserName() {
        lvSelectUserName = new ListView(this);
        //lvSelectUserName.setDivider(getResources().getDrawable(R.drawable.line));
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.item_spinner, userNameList);
        lvSelectUserName.setDivider(getResources().getDrawable(R.drawable.line));
        lvSelectUserName.setAdapter(adapter);
        pw = new PopupWindow(lvSelectUserName, llUserName.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT, true);
        pw.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
        pw.setFocusable(true);
        pw.setOutsideTouchable(true);
        pw.showAsDropDown(llUserName);
        ivSelect.setImageResource(R.drawable.up);
        pw.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                ivSelect.setImageResource(R.drawable.down);
            }
        });
        lvSelectUserName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                etUserName.setText(userNameList.get(position));
                pw.dismiss();
            }
        });
    }

    /**
     * 免登/登录
     */
    private void exempts() {
        //免登设置
        TokenInfo tokenInfo = SpUtil.getObject(mApp, ConfigRes.STORAGE_USER_INFO);
        if (tokenInfo != null) {
            mApp.setTokenInfo(tokenInfo);
            String userName = tokenInfo.getUserName();
            String password = tokenInfo.getPassword();
            if (!TextUtils.isEmpty(userName) && !TextUtils.isEmpty(password)) {
                llContent.setVisibility(View.INVISIBLE);
                login(userName, password);
            } else {
                llContent.setVisibility(View.VISIBLE);
            }
        } else {
            llContent.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 登录
     *
     * @param userName
     * @param password
     */
    private void login(final String userName, final String password) {
        //登录判断
//        if (TextUtils.isEmpty(userName)) {
//            showToastInfo("请输入用户名");
//            return;
//        }
//        if (TextUtils.isEmpty(password)) {
//            showToastInfo("请输入密码");
//            return;
//        }
        //加载中
        final Dialog dialog = DialogUtil.getLoadingDialog(this);
        dialog.show();

        startActivity(new Intent(this, MainActivity.class));
        dialog.dismiss();
        finish();
    }


    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                showToastInfo("再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

}